package com.hkbigdata.streamCoreCoding;

import com.hkbigdata.entry.UserBehavior;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author liuanbo
 * @creat 2023-04-10-13:22
 * @see 2194550857@qq.com
 */
public class Flink02_PageView_WordCount_Process {
    public static void main(String[] args) throws Exception {
        //1.运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.读取数据
        DataStreamSource<String> source = env.readTextFile("input/UserBehavior.csv");

        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMap = source.flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                String[] split = value.split(",");
                //转换为javabean
                UserBehavior userBehavior = new UserBehavior(
                        Long.parseLong(split[0]),
                        Long.parseLong(split[1]),
                        Integer.parseInt(split[2]),
                        split[3],
                        Long.parseLong(split[4])
                );

                if ("pv".equals(userBehavior.getBehavior())) {
                    out.collect(new Tuple2<>("pv", 1));
                }
            }
        });

        KeyedStream<Tuple2<String, Integer>, String> keyedStream = flatMap.keyBy(data -> data.f0);

        SingleOutputStreamOperator<Integer> process = keyedStream.process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Integer>() {
            Integer count = 0;

            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Integer> out) throws Exception {
                count++;
                out.collect(count);
            }
        });

        process.print();

        env.execute();
    }
}
